//package org.example.common.interceptor;
//
//import cn.hutool.core.util.StrUtil;
//import org.example.common.constant.Constants;
//import org.example.common.threadlocal.LogThreadLocal;
//import org.example.common.userinfo.UserService;
//import jodd.net.HttpMethod;
//import lombok.SneakyThrows;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.skywalking.apm.toolkit.trace.TraceContext;
//import org.slf4j.MDC;
//import org.springframework.web.servlet.HandlerInterceptor;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.time.Instant;
//
///**
// * Http拦截器
// *
// * @author zjc
// * @author Jjn
// * @since 2020-08-18 19:35
// */
//@Slf4j
//public class HttpInterceptor implements HandlerInterceptor {
//
//    @Override
//    @SneakyThrows
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
//            return true;
//        }
//
//        LogThreadLocal.setThreadLocal(Instant.now().toEpochMilli());
//
//        String traceId = setTraceId(request);
//        String skyWalkingTraceId = TraceContext.traceId();
//        response.addHeader(Constants.TRACE_ID, StrUtil.isNotBlank(skyWalkingTraceId) ? skyWalkingTraceId : traceId);
//
//        String businessName = UserService.currentBusinessName();
//        MDC.put(Constants.BUSINESS_NAME, businessName);
//
//        String username = UserService.currentUserName();
//        MDC.put(Constants.MDC_USERNAME, username);
//        return true;
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        if (log.isDebugEnabled()) {
//            log.debug("ThreadId:{}", Thread.currentThread().getId());
//        }
//        MDC.remove(Constants.MDC_USERNAME);
//        MDC.remove(Constants.BUSINESS_NAME);
//        TraceIdContext.removeTraceId();
//        LogThreadLocal.remove();
//    }
//
//    private String setTraceId(HttpServletRequest request) {
//        String traceId = request.getHeader(Constants.TRACE_ID);
//        if (StrUtil.isNotBlank(traceId)) {
//            traceId = traceId.replaceAll("[^0-9A-Za-z\\-]", "");
//        } else {
//            traceId = TraceIdContext.createTraceId();
//        }
//        TraceIdContext.setTraceId(traceId);
//        return traceId;
//    }
//}
